<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input placeholder="请输入SPU名称" v-model="spuParams.spuName" />
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select
        placeholder="请选择"
        style="width: 150px"
        v-model="spuParams.tmId"
      >
        <el-option
          v-for="item in allTradeArr"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请输入SPU描述"
        v-model="spuParams.description"
      />
    </el-form-item>
    <el-form-item label="SPU图标">
      <el-upload
        v-model:file-list="imageArr"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 400px; height: 300px"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-select
        :placeholder="
          unSelectSaleAttr.length > 0
            ? `你还有${unSelectSaleAttr.length}未选择`
            : '暂无'
        "
        style="width: 150px"
        v-model="selectSaleAttrIdAndName"
      >
        <el-option
          v-for="item in unSelectSaleAttr"
          :key="item.id"
          :value="`${item.id}:${item.name}`"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-button
        style="margin-left: 10px"
        type="primary"
        icon="Plus"
        @click="addSaleAttr"
        :disabled="selectSaleAttrIdAndName ? false : true"
      >
        添加属性
      </el-button>
      <el-table border style="margin-top: 10px" :data="saleAttrArr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="属性名"
          prop="saleAttrName"
          width="150px"
        ></el-table-column>
        <el-table-column label="属性值">
          <template #="{ row }">
            <el-tag
              v-for="(tag, index) in row.spuSaleAttrValueList"
              :key="tag.id"
              closable
              style="margin: 0 10px"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input
              @blur="blurAttrValue(row)"
              v-model="row.saleAttrValue"
              placeholder="请输入属性值"
              size="small"
              style="width: 120px; margin-right: 10px"
              v-if="row.flag"
            ></el-input>
            <el-button
              v-else
              type="primary"
              size="small"
              icon="Plus"
              @click="addSaleAttrValue(row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px">
          <template #="{ $index }">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="saleAttrArr.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        @click="save"
        :disabled="saleAttrArr.length > 0 ? false : true"
      >
        保存
      </el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {
  SpuData,
  SpuImage,
  SaleAttr,
  HasSaleAttr,
} from '@/api/product/spu/type'
import { Trademark } from '@/api/product/trademark/type'
import {
  reqAllTradeMark,
  reqSpuImage,
  reqSaleAttr,
  reqSaleAttrList,
  reqAddOrUpdateSpu,
} from '@/api/product/spu'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
let $emit = defineEmits(['update:scene'])
const cancel = () => {
  $emit('update:scene', {scene:0,type:"update"})
}
let allTradeArr = ref<Trademark[]>([])
let imageArr = ref<SpuImage[]>([])
let saleAttrArr = ref<SaleAttr[]>([])
let hasSaleAttrArr = ref<HasSaleAttr[]>([])
let selectSaleAttrIdAndName = ref('')
let spuParams = ref<SpuData>({
  spuName: '',
  description: '',
  category3Id: '',
  tmId: '',
  spuSaleAttrList: [],
  spuImageList: [],
})
let dialogVisible = ref(false)
let dialogImageUrl = ref('')
const initSpuData = (row: SpuData) => {
  spuParams.value = row
  Promise.all([
    reqAllTradeMark(),
    reqSpuImage(row.id as number),
    reqSaleAttr(row.id as number),
    reqSaleAttrList(),
  ]).then((res: any) => {
    const [result1, result2, result3, result4] = res
    if (result1.code == 200) {
      allTradeArr.value = result1.data
    }
    if (result2.code == 200) {
      imageArr.value = result2.data.map((img: SpuImage) => {
        return {
          url: img.imgUrl,
          name: img.imgName,
        }
      })
    }
    if (result3.code == 200) {
      saleAttrArr.value = result3.data
    }
    if (result4.code == 200) {
      hasSaleAttrArr.value = result4.data
    }
  })
}
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}
let unSelectSaleAttr = computed(() => {
  let unSelectArr = hasSaleAttrArr.value.filter((has) => {
    return saleAttrArr.value.every((sale) => sale.saleAttrName != has.name)
  })
  return unSelectArr
})

const addSaleAttr = () => {
  let [baseSaleAttrId, saleAttrName] = selectSaleAttrIdAndName.value.split(':')
  saleAttrArr.value.push({
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  })
  selectSaleAttrIdAndName.value = ''
}
const addSaleAttrValue = (row: SaleAttr) => {
  row.flag = true
}
const blurAttrValue = (row: SaleAttr) => {
  row.flag = false
  if (!row.saleAttrValue) {
    return ElMessage({
      type: 'warning',
      message: '属性值不能为空',
    })
  }
  if (
    row.spuSaleAttrValueList.some(
      (item) => item.saleAttrValueName == row.saleAttrValue,
    )
  ) {
    return ElMessage({
      type: 'warning',
      message: '属性值不能重复',
    })
  }
  row.spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.saleAttrValue as string,
  })
  row.saleAttrValue = ''
}
const save = () => {
  spuParams.value.spuImageList = imageArr.value.map((img: any) => {
    return {
      imgName: img.name,
      imgUrl: img.response ? img.response.data : img.url,
    }
  })
  spuParams.value.spuSaleAttrList = saleAttrArr.value
  reqAddOrUpdateSpu(spuParams.value).then((res: any) => {
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: `${spuParams.value.id ? '更新成功' : '添加成功'} `,
      })
      $emit('update:scene', {
        scene: 0,
        type: spuParams.value.id ? 'update' : 'add',
      })
    } else {
      ElMessage({
        type: 'error',
        message: `${spuParams.value.id ? '更新失败' : '添加失败'} `,
      })
    }
  })
}
const initAddSpuData = (c3Id: number) => {
  Object.assign(spuParams.value, {
    spuName: '',
    description: '',
    category3Id: '',
    tmId: '',
    spuSaleAttrList: [],
    spuImageList: [],
  })
  imageArr.value = []
  saleAttrArr.value = []
  selectSaleAttrIdAndName.value = ''
  spuParams.value.id = ''
  spuParams.value.category3Id = c3Id
  Promise.all([reqAllTradeMark(), reqSaleAttrList()]).then((res: any) => {
    const [result1, result2] = res
    if (result1.code == 200) {
      allTradeArr.value = result1.data
    }
    if (result2.code == 200) {
      hasSaleAttrArr.value = result2.data
    }
  })
}
defineExpose({ initSpuData, initAddSpuData })
</script>
<script lang="ts">
export default {
  name: 'SpuForm',
}
</script>
